<template>
  <span ref="addMenuRef">
    <slot></slot>
  </span>
  <div class="context-menu" v-show="showMenu" :style="{ top: `${y}px`, left: `${x}px` }">
    <ul>
      <li v-for="(item, index) in menuItems" :key="index">
        <div v-if="item.type === 'normal'">
          <a href="#" @click="($event) => item.action">{{ item.label }}</a>
        </div>
        <div v-else-if="item.type === 'submenu'">
          <span>{{ item.label }}</span>
          <UseMenu :menuItems="item.children"></UseMenu>
        </div>
        <div v-else-if="item.type === 'separator'">
          <hr />
        </div>
      </li>
    </ul>
  </div>
</template>

<!-- <script lang="ts">
export default {
  name: "UseMenu"
}
</script> -->

<script lang="ts" setup>
import {
  ref,
  onMounted,
  onUnmounted,
  getCurrentInstance,
  type ComponentInternalInstance
} from 'vue'

interface MenuItem {
  type: 'normal' | 'submenu' | 'separator'
  label?: string
  action?: () => void
  children?: MenuItem[]
}

const props = defineProps({
  menuItems: {
    type: Array as () => MenuItem[],
    required: true
  }
})

const that = getCurrentInstance() as ComponentInternalInstance

const showMenu = ref(false)
const x = ref(0)
const y = ref(0)

const handleClick = (event: MouseEvent) => {
  event.preventDefault()
  x.value = event.clientX
  y.value = event.clientY
  showMenu.value = true
}

const handleClose = () => {
  showMenu.value = false
}

onMounted(() => {
  const { ctx } = getCurrentInstance() as any
  console.log('ctx =', ctx)
  console.log('$emitter =', (ctx as any).$emitter)

  const addMenuRef = that.refs.addMenuRef as HTMLElement | null
  if (addMenuRef) {
    addMenuRef.addEventListener('click', handleClose)
    addMenuRef.addEventListener('contextmenu', handleClick)
  }
})

onUnmounted(() => {
  const addMenuRef = that.refs.addMenuRef as HTMLElement | null
  if (addMenuRef) {
    addMenuRef.removeEventListener('click', handleClose)
  }
})
</script>

<style lang="scss">
.context-menu {
  position: absolute;
  z-index: 1000;
  background-color: #fff;
  border: 1px solid #ccc;
  box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.15);

  ul {
    list-style: none;
    margin: 0;
    padding: 0;

    li {
      padding: 6px 12px;
      cursor: pointer;

      &:hover {
        background-color: #f5f5f5;
      }

      a {
        color: #333;
        text-decoration: none;
      }

      span {
        font-weight: bold;
        margin-right: 10px;
      }

      hr {
        margin: 4px 0;
        border: none;
        border-top: 1px solid #ccc;
      }
    }
  }
}
</style>
